<template>
  <div class="app-container">
    <!-- 奖金规则搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
      v-show="showSearch" label-width="68px">
      <el-form-item label="赛事类别">
        <el-select v-model="queryParams.competitionType" placeholder="请选择赛事类别" clearable>
          <el-option v-for="dict in competitionTypeOptions" :key="dict.dictCode" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="赛事级别">
        <el-select v-model="queryParams.competitionGrade" placeholder="请选择赛事级别" clearable>
          <el-option v-for="dict in competitionGradeOptions" :key="dict.dictCode" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="获奖等级">
        <el-select v-model="queryParams.awardGrade" placeholder="请选择获奖等级" clearable>
          <el-option v-for="dict in awardGradeOptions" :key="dict.dictCode" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['rules:bonusrule:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['rules:bonusrule:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['rules:bonusrule:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['rules:bonusrule:import']">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 奖金规则表格 -->
    <el-table v-loading="loading" :data="bonusruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="赛事类别" align="center" prop="competitionTypeName" />
      <el-table-column label="赛事级别" align="center" prop="competitionGradeName" />
      <el-table-column label="获奖等级" align="center" prop="awardGradeName" />
      <el-table-column label="团队类型" align="center" prop="teamTypeName" />
      <el-table-column label="奖金" align="center" prop="amount">
        <template slot-scope="scope">
          {{ formatAmount(scope.row.amount) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['rules:bonusrule:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['rules:bonusrule:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改奖金规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="赛事类别" prop="competitionType">
          <el-select v-model="form.competitionType" placeholder="请选择赛事类别">
            <el-option v-for="dict in competitionTypeOptions" :key="dict.dictCode" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="赛事级别" prop="competitionGrade">
          <el-select v-model="form.competitionGrade" placeholder="请选择赛事级别">
            <el-option v-for="dict in competitionGradeOptions" :key="dict.dictCode" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="获奖等级" prop="awardGrade">
          <el-select v-model="form.awardGrade" placeholder="请选择获奖等级">
            <el-option v-for="dict in awardGradeOptions" :key="dict.dictCode" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队类型" prop="teamType">
          <el-select v-model="form.teamType" placeholder="请选择团队类型">
            <el-option v-for="dict in teamTypeOptions" :key="dict.dictCode" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="奖金" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入奖金" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 奖金规则文件导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的奖金规则
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBonusrule,
  getBonusrule,
  delBonusrule,
  addBonusrule,
  updateBonusrule
} from "@/api/rules/bonusrule";
import { getToken } from "@/utils/auth";

export default {
  name: "Bonusrule",
  // 使用正确的字典类型
  dicts: ["competition_type", "competition_grade", "award_grade", "team_type"],

  data() {
    return {
      // 规则导入参数
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/rules/bonusrule/importData",
      },

      // 字典选项
      competitionTypeOptions: [],
      awardGradeOptions: [],
      competitionGradeOptions: [],
      teamTypeOptions: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 奖金规则表格数据
      bonusruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        competitionType: null,
        competitionGrade: null,
        awardGrade: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        competitionType: [
          { required: true, message: "赛事类别不能为空", trigger: "change" }
        ],
        competitionGrade: [
          { required: true, message: "赛事级别不能为空", trigger: "change" }
        ],
        awardGrade: [
          { required: true, message: "获奖等级不能为空", trigger: "change" }
        ],
        teamType: [
          { required: true, message: "团队类型不能为空", trigger: "change" }
        ],
        amount: [
          { required: true, message: "奖金金额不能为空", trigger: "blur" },
          { pattern: /^[1-9]\d*$/, message: "请输入正确的金额数字", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getList();
    this.loadDictData();
  },
  methods: {
    /** 加载字典数据 */
    loadDictData() {
      console.log('开始加载字典数据...');

      // 加载团队类型字典
      this.getDicts("team_type").then((response) => {
        console.log("团队类型字典:", response.data);
        this.teamTypeOptions = response.data;
      }).catch(error => {
        console.error("加载团队类型字典失败:", error);
        // 设置默认选项
        this.teamTypeOptions = [
          { dictLabel: '指导团队', dictValue: '1' },
          { dictLabel: '参赛团队', dictValue: '2' }
        ];
      });

      // 加载赛事级别字典
      this.getDicts("competition_grade").then((response) => {
        console.log("赛事级别字典:", response.data);
        this.competitionGradeOptions = response.data;
      }).catch(error => {
        console.error("加载赛事级别字典失败:", error);
        this.competitionGradeOptions = [
          { dictLabel: '国家级', dictValue: '0' },
          { dictLabel: '省级', dictValue: '1' },
          { dictLabel: '市级', dictValue: '2' }
        ];
      });

      // 加载获奖等级字典
      this.getDicts("award_grade").then((response) => {
        console.log("获奖等级字典:", response.data);
        this.awardGradeOptions = response.data;
      }).catch(error => {
        console.error("加载获奖等级字典失败:", error);
        this.awardGradeOptions = [
          { dictLabel: '特等奖', dictValue: '0' },
          { dictLabel: '一等奖', dictValue: '1' },
          { dictLabel: '二等奖', dictValue: '2' },
          { dictLabel: '三等奖', dictValue: '3' },
          { dictLabel: '优胜奖', dictValue: '4' }
        ];
      });

      // 加载赛事类别字典
      this.getDicts("competition_type").then((response) => {
        console.log("赛事类别字典:", response.data);
        this.competitionTypeOptions = response.data;
      }).catch(error => {
        console.error("加载赛事类别字典失败:", error);
        this.competitionTypeOptions = [
          { dictLabel: 'A+', dictValue: '1' },
          { dictLabel: 'A', dictValue: '2' },
          { dictLabel: 'B', dictValue: '3' },
          { dictLabel: 'C', dictValue: '4' }
        ];
      });
    },

    /** 查询奖金规则列表 */
    getList() {
      this.loading = true;
      listBonusrule(this.queryParams).then((response) => {
        // 转换字典ID为字典值
        this.bonusruleList = this.convertDictIdsToValues(response.rows);
        this.total = response.total;
        this.loading = false;

        console.log('转换后的奖金规则列表:', this.bonusruleList);
      }).catch(error => {
        console.error('获取奖金规则列表失败:', error);
        this.loading = false;
        this.$modal.msgError('获取奖金规则数据失败');
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        ruleId: null,
        competitionType: null,
        competitionGrade: null,
        awardGrade: null,
        teamType: null,
        amount: null,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ruleId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      // 设置正确的默认值
      this.form = {
        ruleId: null,
        competitionType: '1', // A+
        competitionGrade: '0', // 国家级
        awardGrade: '1', // 一等奖
        teamType: '1', // 指导团队
        amount: 10000,
      };

      this.open = true;
      this.title = "添加奖金规则";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids;
      getBonusrule(ruleId).then((response) => {
        // 转换字典ID为字典值
        this.form = this.convertDictIdsToValues([response.data])[0];
        this.open = true;
        this.title = "修改奖金规则";
      }).catch(error => {
        console.error('获取奖金规则详情失败:', error);
        this.$modal.msgError('获取规则详情失败');
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 调试：查看实际提交的数据
          console.log('准备提交的表单数据:', this.form);

          // 严格验证字典值
          if (!this.strictValidateDictValues(this.form)) {
            return;
          }

          // 清洗数据并转换字典值为字典ID
          const cleanedForm = this.cleanFormData(this.form);
          const finalForm = this.convertDictValuesToIds(cleanedForm);

          console.log('最终提交的数据:', finalForm);

          if (finalForm.ruleId != null) {
            updateBonusrule(finalForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('修改奖金规则失败:', error);
              this.$modal.msgError('修改失败');
            });
          } else {
            addBonusrule(finalForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('新增奖金规则失败:', error);
              this.$modal.msgError('新增失败');
            });
          }
        }
      });
    },

    /** 严格验证字典值 */
    strictValidateDictValues(form) {
      const validations = [
        {
          field: 'competitionType',
          name: '赛事类别',
          options: this.competitionTypeOptions,
          value: form.competitionType
        },
        {
          field: 'competitionGrade',
          name: '赛事级别',
          options: this.competitionGradeOptions,
          value: form.competitionGrade
        },
        {
          field: 'awardGrade',
          name: '获奖等级',
          options: this.awardGradeOptions,
          value: form.awardGrade
        },
        {
          field: 'teamType',
          name: '团队类型',
          options: this.teamTypeOptions,
          value: form.teamType
        }
      ];

      for (const validation of validations) {
        if (!validation.value && validation.value !== '0') {
          this.$modal.msgError(`请选择${validation.name}`);
          return false;
        }

        const validOption = validation.options.find(opt => opt.dictValue == validation.value);
        if (!validOption) {
          console.error(`无效的${validation.name}值:`, validation.value, '可用选项:', validation.options);
          this.$modal.msgError(`请选择有效的${validation.name}，当前值"${validation.value}"无效`);
          return false;
        }

        console.log(`${validation.name}验证通过:`, validation.value, '->', validOption.dictLabel);
      }

      return true;
    },

    /** 清洗表单数据 */
    cleanFormData(form) {
      const cleaned = { ...form };

      // 确保金额是数字
      if (cleaned.amount) {
        cleaned.amount = parseInt(cleaned.amount) || 0;
      }

      return cleaned;
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm("确认删除选中的奖金规则？").then(() => {
        return delBonusrule(ruleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "奖金规则导入";
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "rules/bonusrule/importTemplate",
        {},
        `奖金规则模板_${new Date().getTime()}.xlsx`
      );
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 格式化金额显示
    formatAmount(amount) {
      if (!amount) return '0';
      return Number(amount).toLocaleString('zh-CN');
    },

    /** 转换字典ID为字典值 */
    convertDictIdsToValues(data) {
      if (!data || !Array.isArray(data)) return data;

      // 根据你的字典表数据创建映射
      const dictMappings = {
        competition_type: {
          105: '1', // A+
          104: '2', // A
          113: '3', // B
          114: '4'  // C
        },
        competition_grade: {
          100: '0', // 国家级
          101: '1', // 省级
          102: '2'  // 市级
        },
        award_grade: {
          106: '0', // 特等奖
          107: '1', // 一等奖
          108: '2', // 二等奖
          109: '3', // 三等奖
          110: '4'  // 优胜奖
        },
        team_type: {
          111: '1', // 指导团队
          112: '2'  // 参赛团队
        }
      };

      return data.map(item => {
        const converted = { ...item };

        // 转换字段
        if (converted.competitionType && dictMappings.competition_type[converted.competitionType]) {
          converted.competitionType = dictMappings.competition_type[converted.competitionType];
        }

        if (converted.competitionGrade && dictMappings.competition_grade[converted.competitionGrade]) {
          converted.competitionGrade = dictMappings.competition_grade[converted.competitionGrade];
        }

        if (converted.awardGrade && dictMappings.award_grade[converted.awardGrade]) {
          converted.awardGrade = dictMappings.award_grade[converted.awardGrade];
        }

        if (converted.teamType && dictMappings.team_type[converted.teamType]) {
          converted.teamType = dictMappings.team_type[converted.teamType];
        }

        return converted;
      });
    },

    /** 转换字典值为字典ID（用于提交） */
    convertDictValuesToIds(formData) {
      const converted = { ...formData };

      // 反向映射
      const reverseMappings = {
        competition_type: {
          '1': 105, // A+
          '2': 104, // A
          '3': 113, // B
          '4': 114  // C
        },
        competition_grade: {
          '0': 100, // 国家级
          '1': 101, // 省级
          '2': 102  // 市级
        },
        award_grade: {
          '0': 106, // 特等奖
          '1': 107, // 一等奖
          '2': 108, // 二等奖
          '3': 109, // 三等奖
          '4': 110  // 优胜奖
        },
        team_type: {
          '1': 111, // 指导团队
          '2': 112  // 参赛团队
        }
      };

      // 转换字段
      if (converted.competitionType && reverseMappings.competition_type[converted.competitionType]) {
        converted.competitionType = reverseMappings.competition_type[converted.competitionType];
      }

      if (converted.competitionGrade && reverseMappings.competition_grade[converted.competitionGrade]) {
        converted.competitionGrade = reverseMappings.competition_grade[converted.competitionGrade];
      }

      if (converted.awardGrade && reverseMappings.award_grade[converted.awardGrade]) {
        converted.awardGrade = reverseMappings.award_grade[converted.awardGrade];
      }

      if (converted.teamType && reverseMappings.team_type[converted.teamType]) {
        converted.teamType = reverseMappings.team_type[converted.teamType];
      }

      return converted;
    },
  },
};
</script>

<style scoped>
.el-upload__tip {
  line-height: 1.5;
}

.text-center {
  text-align: center;
}
</style>
